package ntancnit.app.whereareyou;

import java.util.ArrayList;
import java.util.List;

import ntancnit.app.map.GMapV2GetRouteDirection;
import ntancnit.app.network.Config;

import org.w3c.dom.Document;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;

@SuppressLint("NewApi")
public class FriendActivity extends FragmentActivity implements
		LocationListener, ConnectionCallbacks, OnConnectionFailedListener,
		OnClickListener {

	List<Overlay> mapOverlays;
	GeoPoint point1, point2;
	LocationManager locManager;
	Drawable drawable;
	Document document;
	GMapV2GetRouteDirection v2GetRouteDirection;
	LatLng fromPosition;
	LatLng toPosition;
	GoogleMap mGoogleMap;
	MarkerOptions markerOptions;
	Location location, curLocation;
	LatLng desLatLng;
	private GoogleMap map;
	private LocationClient mLocationClient;
	private static final LocationRequest REQUEST = LocationRequest.create()
			.setInterval(5000) // 5 seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	Button btngetRoute;
	Boolean isRoutePressed = false;
	Boolean isLoadRoue = false;
	private ProgressDialog ringProgressDialog;
	private AdView adView;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.friend_layout);
		setUpGoogleMap(getIntentInfomation());
		posision pos = getIntentInfomation();
		desLatLng = new LatLng(pos.lat, pos.lng);
		setUpLocationClientIfNeeded();
		mLocationClient.connect();

		btngetRoute = (Button) findViewById(R.id.button1);
		btngetRoute.setOnClickListener(this);

		adView = new AdView(this);
	    adView.setAdSize(AdSize.BANNER);
	    adView.setAdUnitId(Config.AD_UNIT_ID);

	    LinearLayout layout = (LinearLayout) findViewById(R.id.liner);
	    layout.addView(adView);
	    AdRequest adRequest = new AdRequest.Builder()
	        .build();
	    adView.loadAd(adRequest);
	}

	@Override
	public void onPause() {
		mLocationClient.disconnect();
		if (map != null)
			map.setMyLocationEnabled(false);
		super.onPause();
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
					this);
		}
	}

	private void setUpGoogleMap(posision pos) {
		if (map == null)
			map = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.mapf)).getMap();
		if (map != null) {
			map.setMyLocationEnabled(true);
			MarkerOptions marker = new MarkerOptions().position(
					new LatLng(pos.lat, pos.lng)).title(
					pos.name + getString(R.string.shareContent) + pos.content);
			Marker m = map.addMarker(marker);
			m.showInfoWindow();
			CameraPosition camera = new CameraPosition.Builder()
					.target(new LatLng(pos.lat, pos.lng)).zoom(15).build();
			map.animateCamera(CameraUpdateFactory.newCameraPosition(camera));
		}
	}

	private posision getIntentInfomation() {
		posision pos = new posision();
		Double lat = Double.parseDouble(getIntent().getStringExtra("lat"));
		Double lng = Double.parseDouble(getIntent().getStringExtra("lng"));
		String name = getIntent().getStringExtra("name");
		String content = getIntent().getStringExtra("content");
		pos.lat = lat;
		pos.lng = lng;
		pos.name = name;
		pos.content = content;
		return pos;
	}

	private class posision {
		private Double lat;
		private Double lng;
		private String name;
		private String content;
	}

	/**
	 * 
	 * @author Thanh An
	 * 
	 */
	private class GetRouteTask extends AsyncTask<String, Void, String> {

		String response = "";

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... urls) {
			document = v2GetRouteDirection.getDocument(fromPosition,
					toPosition, GMapV2GetRouteDirection.MODE_DRIVING);
			response = "Success";
			return response;

		}
		@Override
		protected void onPostExecute(String result) {
			mGoogleMap.clear();
			if (response.equalsIgnoreCase("Success")) {
				ArrayList<LatLng> directionPoint = v2GetRouteDirection
						.getDirection(document);
				PolylineOptions rectLine = new PolylineOptions().width(10)
						.color(Color.RED);

				for (int i = 0; i < directionPoint.size(); i++) {
					rectLine.add(directionPoint.get(i));
				}
				mGoogleMap.addPolyline(rectLine);
				markerOptions.position(toPosition);
				markerOptions.draggable(true);
				mGoogleMap.addMarker(markerOptions);
				isLoadRoue = true;
				if (ringProgressDialog.isShowing())
					ringProgressDialog.dismiss();
			}
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}

	@Override
	public void onLocationChanged(Location arg0) {
		if (isRoutePressed && !isLoadRoue) {
			curLocation = mLocationClient.getLastLocation();
			if (curLocation != null) {
				v2GetRouteDirection = new GMapV2GetRouteDirection();
				mGoogleMap = ((MapFragment) getFragmentManager()
						.findFragmentById(R.id.mapf)).getMap();
				if (mGoogleMap != null) {
					mGoogleMap.setMyLocationEnabled(true);
					mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
					mGoogleMap.getUiSettings().setCompassEnabled(true);
					mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
					mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
					mGoogleMap.setTrafficEnabled(true);
					mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
					markerOptions = new MarkerOptions();
					fromPosition = new LatLng(curLocation.getLatitude(),
							curLocation.getLongitude());
					toPosition = new LatLng(desLatLng.latitude,
							desLatLng.longitude);
					GetRouteTask getRoute = new GetRouteTask();
					getRoute.execute();
				}
			}
		}
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {

	}

	@Override
	public void onConnected(Bundle arg0) {
		mLocationClient.requestLocationUpdates(REQUEST, this);

	}

	@Override
	public void onDisconnected() {
	}

	@Override
	public void onClick(View v) {
		if (v == btngetRoute) {
			isRoutePressed = true;
			isLoadRoue = false;
			ringProgressDialog = ProgressDialog.show(FriendActivity.this,
					getString(R.string.waiting), getString(R.string.process), true);
			ringProgressDialog.setCancelable(true);
		}

	}

}
